package net.sk.china.platform.service.impl.system;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sk.china.platform.dao.system.SystemNotificationDao;
import net.sk.china.platform.model.system.SystemNotification;
import net.sk.china.platform.model.wechat.TemplateMessage;
import net.sk.china.platform.request.notification.NotificationInfoRequest;
import net.sk.china.platform.request.notification.NotificationSearchRequest;
import net.sk.china.platform.request.notification.NotificationUpdateRequest;
import net.sk.china.platform.response.NotificationInfoResponse;
import net.sk.china.platform.service.system.SystemNotificationService;
import net.sk.china.platform.service.wechat.TemplateMessageService;
import net.sk.china.common.exception.TalkException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * SystemNotificationServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/6/3 17:17
 * // +----------------------------------------------------------------------
 */

@Service
public class SystemNotificationServiceImpl extends ServiceImpl<SystemNotificationDao, SystemNotification> implements SystemNotificationService {

    @Resource
    private SystemNotificationDao dao;

    private final TemplateMessageService templateMessageService;

    private final TransactionTemplate transactionTemplate;

    public SystemNotificationServiceImpl(TemplateMessageService templateMessageService, TransactionTemplate transactionTemplate) {
        this.templateMessageService = templateMessageService;
        this.transactionTemplate = transactionTemplate;
    }

    /**
     * 系统通知列表
     * @param request 查询对象
     * @return {@code List<SystemNotification>}
     */
    @Override
    public List<SystemNotification> getList(NotificationSearchRequest request) {
        LambdaQueryWrapper<SystemNotification> query = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotNull(request.getSendType())) {
            query.eq(SystemNotification::getSendType, request.getSendType());
        }
        return dao.selectList(query);
    }

    /**
     * 公众号模板开关
     * @param id 通知id
     * @return {@code boolean}
     */
    @Override
    public boolean wechatSwitch(Integer id) {
        SystemNotification systemNotification = getByIdException(id);
        if (systemNotification.getIsWechat().equals(0)) {
            throw new TalkException("通知没有配置公众号模板");
        }
        LambdaUpdateWrapper<SystemNotification> query = Wrappers.lambdaUpdate();
        query.set(SystemNotification::getIsWechat, systemNotification.getIsWechat().equals(1) ? 2 : 1);
        query.eq(SystemNotification::getId, id);
        return update(query);
    }

    /**
     * 小程序订阅模板开关
     * @param id 通知id
     * @return {@code boolean}
     */
    @Override
    public Boolean routineSwitch(Integer id) {
        SystemNotification systemNotification = getByIdException(id);
        if (systemNotification.getIsRoutine().equals(0)) {
            throw new TalkException("通知没有配置小程序订阅模板");
        }
        LambdaUpdateWrapper<SystemNotification> query = Wrappers.lambdaUpdate();
        query.set(SystemNotification::getIsRoutine, systemNotification.getIsRoutine().equals(1) ? 2 : 1);
        query.eq(SystemNotification::getId, id);
        return update(query);
    }

    /**
     * 发送短信开关
     * @param id 通知id
     * @return {@code boolean}
     */
    @Override
    public Boolean smsSwitch(Integer id) {
        SystemNotification systemNotification = getByIdException(id);
        if (systemNotification.getIsSms().equals(0)) {
            throw new TalkException("通知没有配置短信");
        }
        LambdaUpdateWrapper<SystemNotification> query = Wrappers.lambdaUpdate();
        query.set(SystemNotification::getIsSms, systemNotification.getIsSms().equals(1) ? 2 : 1);
        query.eq(SystemNotification::getId, id);
        return update(query);
    }

    /**
     * 通知详情
     * @param request 详情请求参数
     * @return {@code NotificationInfoResponse}
     */
    @Override
    public NotificationInfoResponse getDetail(NotificationInfoRequest request) {
        SystemNotification notification = getByIdException(request.getId());
        NotificationInfoResponse response = new NotificationInfoResponse();
        String wechat = "wechat";
        if (request.getDetailType().equals(wechat)) {
            if (notification.getIsWechat().equals(0)) {
                throw new TalkException("请先配置公众号模板消息");
            }
            TemplateMessage templateMessage = templateMessageService.info(notification.getWechatId());
            if (ObjectUtil.isNull(templateMessage)) {
                throw new TalkException("微信模版消息不存在，请核实");
            }
            BeanUtils.copyProperties(templateMessage, response);
            response.setStatus(notification.getIsWechat());
        }
        String routine = "routine";
        if (request.getDetailType().equals(routine)) {
            if (notification.getIsRoutine().equals(0)) {
                throw new TalkException("请先配置小程序订阅消息");
            }
            TemplateMessage templateMessage = templateMessageService.info(notification.getRoutineId());
            if (ObjectUtil.isNull(templateMessage)) {
                throw new TalkException("小程序订阅消息不存在，请核实");
            }
            BeanUtils.copyProperties(templateMessage, response);
            response.setStatus(notification.getIsRoutine());
        }
        String sms = "sms";
        if (request.getDetailType().equals(sms)) {
            throw new TalkException("短信模版正在开发中");
        }
        return response;
    }

    /**
     * 根据标识查询信息
     * @param mark 标识
     * @return {@code SystemNotification}
     */
    @Override
    public SystemNotification getByMark(String mark) {
        LambdaQueryWrapper<SystemNotification> query = Wrappers.lambdaQuery();
        query.eq(SystemNotification::getMark, mark);
        return dao.selectOne(query);
    }

    /**
     * 获取微信相关列表
     * @param type routine-小程序，public-公众号
     * @return {@code  List<SystemNotification>}
     */
    @Override
    public List<SystemNotification> getListByWechat(String type) {
        LambdaQueryWrapper<SystemNotification> query = Wrappers.lambdaQuery();
        String routine = "routine";
        if (routine.equals(type)) {
            query.ne(SystemNotification::getIsRoutine, 0);
        }
        String wechat = "public";
        if (wechat.equals(type)) {
            query.ne(SystemNotification::getIsWechat, 0);
        }
        return dao.selectList(query);
    }

    /**
     * 修改通知
     * @param request 请求参数
     * @return {@code Boolean}
     */
    @Override
    public Boolean modify(NotificationUpdateRequest request) {
        if (StrUtil.isEmpty(request.getTempId())) {
            throw new TalkException("模板id不能为空");
        }
        SystemNotification notification = getByIdException(request.getId());
        String wechat = "wechat";
        if (request.getDetailType().equals(wechat)) {
            if (notification.getIsWechat().equals(0)) {
                throw new TalkException("请先为通知配置公众号模板");
            }
            TemplateMessage templateMessage = templateMessageService.info(notification.getWechatId());
            if (templateMessage.getTempId().equals(request.getTempId()) && notification.getIsWechat().equals(request.getStatus())) {
                return true;
            }
            return transactionTemplate.execute(e -> {
                if (!templateMessage.getTempId().equals(request.getTempId())) {
                    templateMessage.setTempId(request.getTempId());
                    templateMessageService.updateById(templateMessage);
                }
                if (!notification.getIsWechat().equals(request.getStatus())) {
                    notification.setIsWechat(request.getStatus());
                    updateById(notification);
                }
                return Boolean.TRUE;
            });
        }
        String routine = "routine";
        if (request.getDetailType().equals(routine)) {
            if (notification.getIsRoutine().equals(0)) {
                throw new TalkException("请先为通知配置小程序订阅模板");
            }
            TemplateMessage templateMessage = templateMessageService.info(notification.getRoutineId());
            if (templateMessage.getTempId().equals(request.getTempId()) && notification.getIsRoutine().equals(request.getStatus())) {
                return true;
            }
            return transactionTemplate.execute(e -> {
                if (!templateMessage.getTempId().equals(request.getTempId())) {
                    templateMessage.setTempId(request.getTempId());
                    templateMessageService.updateById(templateMessage);
                }
                if (!notification.getIsRoutine().equals(request.getStatus())) {
                    notification.setIsRoutine(request.getStatus());
                    updateById(notification);
                }
                return Boolean.TRUE;
            });
        }
        String sms = "sms";
        if (request.getDetailType().equals(sms) && !notification.getIsSms().equals(request.getStatus())) {
            throw new TalkException("短信模版正在开发中");
        }
        return true;
    }

    /**
     * 获取单个系统通知数据
     * @param id 数据ID
     * @return SystemNotification
     */
    private SystemNotification getByIdException(Integer id) {
        SystemNotification notification = getById(id);
        if (ObjectUtil.isNull(notification)) {
            throw new TalkException("系统通知不存在");
        }
        return notification;
    }
}
